package org.kent.w.base.common.validate.validator;

import lombok.extern.slf4j.Slf4j;
import org.kent.w.base.common.enums.IntEnum;
import org.kent.w.base.common.validate.constraints.IntEnumValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Enum Value ConstraintValidator
 *
 * @author wujigang
 * @date 2019/9/17
 */
@Slf4j
public class IntEnumValueConstraintValidator implements ConstraintValidator<IntEnumValue, Integer> {

    private Class<? extends IntEnum> enumClass;

    @Override
    public void initialize(IntEnumValue intEnumValue) {
        this.enumClass = intEnumValue.enumClass();
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {

        if (value == null || enumClass == null) {
            return false;
        }

        IntEnum[] enumConstants = enumClass.getEnumConstants();

        for (IntEnum e : enumConstants) {
            if (e.getCode() == value) {
                return true;
            }
        }

        return false;
    }
}
